package element.synt;

import ast.AstItem;
import ast.Expression;
import element.base.Synt;
import element.base.Word;
import element.base.WordType;

public class MulExp extends Synt {
    @Override
    public AstItem toAst() {
        if (getNodes().size() == 1) {
            UnaryExp unaryExp = (UnaryExp) getNodes().getFirst();
            Expression expression = (Expression) unaryExp.toAst();
            expression.allUnaryExp = ((Expression) unaryExp.toAst()).allUnaryExp;
            return expression;
        } else {
            MulExp mulExp = (MulExp) getNodes().getFirst();
            UnaryExp unaryExp = (UnaryExp) getNodes().getLast();

            Expression expression = new Expression();
            Word op = (Word) getNodes().get(1);
            if (op.isWord(WordType.MULT)) {
                expression.operator = Expression.OperatorType.OP_MUL;
            } else if (op.isWord(WordType.DIV)) {
                expression.operator = Expression.OperatorType.OP_DIV;
            } else {
                expression.operator = Expression.OperatorType.OP_MOD;
            }
            expression.operands.add(mulExp.toAst());
            expression.operands.add(unaryExp.toAst());

            for (AstItem unary: ((Expression) mulExp.toAst()).allUnaryExp) {
                expression.allUnaryExp.add(unary);
            }

            expression.allUnaryExp.add((Expression) unaryExp.toAst());

            return expression;
        }
    }
}
